<template>
  <div>
    <!--<a-row>
      <a-col :span="24">
        <a-form-model-item label="巡检图片" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fileList">

        </a-form-model-item>
      </a-col>
    </a-row>-->
    <div class="clearfix">
      <a-upload
        :action="uploadAction"
        :beforeUpload="doBeforeUpload"
        list-type="picture-card"
        :file-list="fileList"
        :headers="headers"
        :data="{'biz':'temp'}"
        :returnUrl="returnUrl"
        @preview="handlePreview"
        @change="handleChange"
      >
        <div v-if="fileList.length < 8">
          <a-icon type="plus"/>
          <div class="ant-upload-text">
            上传
          </div>
        </div>
      </a-upload>
      <!--<a-modal :visible="previewVisible" :footer="null" @cancel="handleClose">
        <img alt="example" style="width: 100%" :src="previewImage"/>
      </a-modal>-->

      <a-modal class="img-style" :visible="previewVisible" :footer="null" centered width="auto" @cancel="handleClose">
        <JReview :path="previewImage" :pathList="imgList"></JReview>
      </a-modal>
    </div>
  </div>
</template>

<script>
  import Vue from "vue";
  import { httpAction, putAction,getAction,getFileAccessHttpUrl } from '@/api/manage'
  import {ACCESS_TOKEN} from "@/store/mutation-types"

  export default {
    name: "inspectionImageTab",
    props: {
      record: {}
    },
    data() {
      return {
        title: '',
        width: 800,
        visible: false,
        disableSubmit: false,
        customerId: '',
        fileList: [],
        newFileList: [],
        oldFileList: [],  //存放点击修改按钮带过来的所有图片
        imgList:[],
        previewVisible: false,
        previewImage: '',
        uploadAction: window._CONFIG['domianURL'] + "/sys/oss/file/upload",
        headers: {},
        returnUrl: {
          type: Boolean,
          required: false,
          default: true
        },
        uploadGoOn: true,
        model: {},
        labelCol: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
        confirmLoading: false,
        url: {
          add: "/ghSiteCircuit/add",
          edit: "/ghSiteCircuit/edit",
          queryById: "/ghSiteCircuit/queryById"
        }
      }
    },
    watch:{
      //监听record值的变化，变化则加载新的数据
      record:function(newVal,oldVal){
        //console.log(newVal +"---"+oldVal)
        this.fileList = [];
        this.loadData()
      },
    },
    created() {
      const token = Vue.ls.get(ACCESS_TOKEN);
      this.headers = {"X-Access-Token": token}
      //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      this.loadData()
    },
    methods: {
      close () {
        this.$emit('close');
        this.visible = false;
        this.oldFileList = [];
        this.fileList = [];
      },

      loadData(){
        this.model = Object.assign({}, this.record);
        this.visible = true;
        this.oldFileList = this.record.images;
        if (this.oldFileList != null){
          for (let i=0;i<this.oldFileList.length;i++){
            if (this.oldFileList[i] !== ""){
              let file = {key:(i+1),uid:(i+1),name:this.oldFileList[i],url:getFileAccessHttpUrl(this.oldFileList[i]),response:{message:this.oldFileList[i],result:this.oldFileList[i]}}
              this.fileList.push(file)
            }
          }
        }
      },

      handleOk () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
              method = 'put';
            }
            let images = "";
            if (!this.model.id){
              for (let i = 0; i < this.fileList.length; i++) {
                images += this.fileList[i].url + ",";
              }
              this.model.circuitImg = images;
            }else {
              if (this.oldFileList != null){
                if ( this.oldFileList.length > this.fileList.length){
                  for (let i=0;i<this.fileList.length;i++){
                    images += this.fileList[i].response.message + ",";
                  }
                  this.model.circuitImg = images;
                }else {
                  //修改之添加图片
                  for (let i=0;i<this.fileList.length;i++){
                    if (this.fileList[i].name != this.oldFileList[i]){
                      this.oldFileList.push(this.fileList[i].response.message);
                    }
                  }
                  for (let i = 0; i < this.oldFileList.length; i++) {
                    images += this.oldFileList[i] + ",";
                  }
                  this.model.circuitImg = images;
                }
              }else {
                for (let i = 0; i < this.fileList.length; i++) {
                  images += this.fileList[i].response.message + ",";
                }
                this.model.circuitImg = images;
              }
            }

            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              this.close();
            })
          }
        })
      },

      handleCancel () {
        this.close()
      },

      async handlePreview(file) {
        if (!file.response.result && !file.preview) {
          file.preview = await getBase64(file.originFileObj);
        }
        let imgList = [];
        for (let i=0;i<this.fileList.length;i++){
          imgList.push(this.fileList[i].url);
        }
        this.imgList = imgList;
        this.previewImage = file.response.result || file.preview;
        this.previewVisible = true;
      },
      doBeforeUpload(file){
        var fileType = file.type;
        if (fileType.indexOf('image')<0){
          this.$message.warning('请上传图片');
          this.uploadGoOn=false
          return false;
        }
        const isLt10M = file.size / 1024 / 1024 < 10
        if (!isLt10M) {
          this.$message.error('上传文件大小不能超过 10MB!')
          this.uploadGoOn=false
          return false;
        }
        return true;
      },
      handleChange(info) {
        console.log("--文件列表改变--")
        if (!info.file.status && this.uploadGoOn === false) {
          info.fileList.pop();
        }
        let fileList = info.fileList
        if (info.file.status === 'done') {
          if (this.number > 0) {
            fileList = fileList.slice(-this.number);
          }
          if (info.file.response.success) {
            fileList = fileList.map((file) => {
              if (file.response) {
                // let reUrl = file.response.message;
                // file.url = getFileAccessHttpUrl(reUrl);
                file.url = file.response.result;
              }
              return file;
            });
          }
          //this.$message.success(`${info.file.name} 上传成功!`);
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败.`);
        } else if (info.file.status === 'removed') {
          //this.handleDelete(info.file)
          //this.deleteImage(info.file)
        }
        this.fileList = fileList
        if (info.file.status === 'done' || info.file.status === 'removed') {
          //returnUrl为true时仅返回文件路径
          if (this.returnUrl) {
            this.handlePathChange()
          } else {
            //returnUrl为false时返回文件名称、文件路径及文件大小
            this.newFileList = [];
            for (var a = 0; a < fileList.length; a++) {
              // update-begin-author:lvdandan date:20200603 for:【TESTA-514】【开源issue】多个文件同时上传时，控制台报错
              if (fileList[a].status === 'done') {
                var fileJson = {
                  fileName: fileList[a].name,
                  filePath: fileList[a].response.message,
                  fileSize: fileList[a].size
                };
                this.newFileList.push(fileJson);
              } else {
                return;
              }
              // update-end-author:lvdandan date:20200603 for:【TESTA-514】【开源issue】多个文件同时上传时，控制台报错
            }
            this.$emit('change', this.newFileList);
          }
        }
      },
      handlePathChange() {
        let uploadFiles = this.fileList
        let path = ''
        if (!uploadFiles || uploadFiles.length == 0) {
          path = ''
        }
        let arr = [];
        if (!this.isMultiple && uploadFiles.length > 0) {
          arr.push(uploadFiles[uploadFiles.length - 1].response.message)
        } else {
          for (let a = 0; a < uploadFiles.length; a++) {
            // update-begin-author:taoyan date:20200819 for:【开源问题z】上传图片组件 LOWCOD-783
            if (uploadFiles[a].status === 'done') {
              arr.push(uploadFiles[a].response.message)
            } else {
              return;
            }
            // update-end-author:taoyan date:20200819 for:【开源问题z】上传图片组件 LOWCOD-783
          }
        }
        if (arr.length > 0) {
          path = arr.join(",")
        }
        this.$emit('change', path);
        let imgUrl = "";
        for (let i=0;i<this.fileList.length;i++){
          imgUrl += this.fileList[i].url;
          imgUrl += ",";
        }
        let params = {};
        params.id = this.record.id;
        params.circuitImg = imgUrl;
        putAction(this.url.edit,params).then((res) => {
          if (res.success) {
            this.$message.success(res.message);
          } else {
            this.$message.warning(res.message);
          }
        })
      },
      //关闭预览照片
      handleClose() {
        this.previewVisible = false;
      },
      handleDelete(file){
        //console.log("=========="+file)
      }
    }
  }
</script>

<style lang="less" scoped>
  .img-style /deep/ .ant-modal-content{
    background-color:rgba(0,0,0, 0) !important;
    box-shadow: none;

  }
</style>